package respository

import (
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/vo"
	"gorm.io/gorm"
	"log"
)

//定义接口和定义增删改查的方法
type ITsRepository interface {
	Create(ts model.Ts)
	Update(ts model.Ts)
	SelectById(Id int64)
	DeleteById(Id int64)
	List(tsList vo.TsList)
}

type TsRepository struct {
	DB *gorm.DB
}

func (t TsRepository) Create(ts model.Ts) (int64, error){

	if err := t.DB.Preload("Fct").Preload("Scene").Create(&ts).Error; err != nil {
		log.Printf("新增失败，错误信息为：%v",err)
		return 0, err
	}

	return ts.ID, nil
}

func (t TsRepository) Update(ts model.Ts) (*model.Ts, error){
	log.Println("ts:",ts,&ts)
	if err := t.DB.UpdateColumns(&ts).Error;err != nil {
		return nil, err
	}

	return &ts, nil
}


func (t TsRepository) SelectById(Id int64) (*model.Ts, error){
	var ts model.Ts

	if err := t.DB.Preload("Fct").Preload("Scene").Where("id = ?",Id).First(&ts).Error; err != nil{
		return nil, err
	}

	return &ts, nil
}

func (t TsRepository) DeleteById(Id int64) (rowsAffected int64) {

	rowsAffected = t.DB.Where("id = ?", Id).Delete(model.Scene{}).RowsAffected
	if rowsAffected != 1 {
		log.Printf("数据删除失败，删除操作影响行数为：%v，删除的id为：%v",rowsAffected,Id)
	}

	return
}

func (t TsRepository) List(tsList vo.TsList) (ts []model.Ts, total int64){

	// 条件查询
	//if tsList.SceneId > 0  {
	//	t.DB = t.DB.Where("scene_id = ?", tsList.SceneId)
	//}
	if tsList.FctId > 0  {
		t.DB = t.DB.Where("fct_id = ?", tsList.FctId)
	}
	if tsList.Name != ""  {
		t.DB = t.DB.Where("name like ?", "%" + tsList.Name + "%")
	}
	if tsList.PageNum == 0  {
		tsList.PageNum = 1
	}
	if tsList.PageSize == 0  {
		tsList.PageSize = 10
	}

	//总记录数
	t.DB.Model(model.Ts{}).Count(&total)
	if total == 0 {
		return
	}

	t.DB.Preload("Fct").Preload("Scene").Order("created_at desc").
		Offset((tsList.PageNum -1) * tsList.PageSize).Limit(tsList.PageSize).Find(&ts)

	return
}

func NewTsRepository() TsRepository{
	db := common.GetDB()
	//db.AutoMigrate(model.Ts{})

	return TsRepository{DB: db}
}